package com.study.quiz.controller;

import com.study.quiz.dto.CommentDTO;
import com.study.quiz.dto.CommentResponseDTO;
import com.study.quiz.dto.ResultDTO;
import com.study.quiz.enums.CommentTypeEnum;
import com.study.quiz.enums.ResultMsgEnum;
import com.study.quiz.pojo.Comment;
import com.study.quiz.pojo.User;
import com.study.quiz.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author CJunGod
 * @create 2020-03-08 22:12
 **/
@Slf4j
@Controller
public class CommentController {

    @Resource
    private CommentService commentService;

    @ResponseBody
    @PostMapping("/comment")
    public ResultDTO postComment(CommentDTO commentDTO, HttpServletRequest request) {

        User user = (User) request.getSession().getAttribute("user");
        ResultDTO resultDTO = new ResultDTO();
        if (user == null) {
            return resultDTO.indexOfMsg(ResultMsgEnum.ERROR_USER_ISNULL);
        }

        if (commentDTO.getParentId() == null || commentDTO.getParentId() == 0) {
            return resultDTO.indexOfMsg(ResultMsgEnum.ERROR_COMMENT_PARAM_ISNULL);
        }

        if (commentDTO.getType() == null || !CommentTypeEnum.isExist(commentDTO.getType())) {
            return resultDTO.indexOfMsg(ResultMsgEnum.ERROR_COMMENT_TYPE_FOUND);
        }
        Comment comment = new Comment();
        comment.setParentId(commentDTO.getParentId());
        comment.setContent(commentDTO.getContent());
        comment.setType(commentDTO.getType());
        comment.setGmtCreate(System.currentTimeMillis());
        comment.setGmtModified(System.currentTimeMillis());
        comment.setCommentator(user.getId());
        comment.setStatus(true);
        if(commentService.insert(comment, user, commentDTO.getQuestionId()) > 0){
            return resultDTO.isOk();
        }

        return resultDTO.indexOfMsg(ResultMsgEnum.ERROR_COMMENT_MESSAGE);
    }

    @ResponseBody
    @GetMapping("/comment/{id}")
    public ResultDTO comments(@PathVariable("id")Integer commentId){
        List<CommentResponseDTO> commentResponseDTOS = commentService.listByTargetId(commentId, CommentTypeEnum.COMMENT.getType());

        return ResultDTO.isOk(commentResponseDTOS);
    }
}

